<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <input id="sendTxt" type="text">
    <button id="sendMessage">发送</button>
    <div id="infoBox"></div>
    <script>
        // 创建WebSoket对象
        var ws = new WebSocket('ws://localhost:5852')

        // 连接建立时触发
        ws.onopen = function () {
            console.log('WebSocket已连接')
            document.getElementById('infoBox').innerHTML = '已连接'
            // 使用连接发送数据
            // ws.send('hello')
        }
        
        // 客户端接收服务端数据时触发
        ws.onmessage = function (msg) {
            console.log(msg)

            // 关闭连接
            ws.close()
        }

        // 通信发生错误时触发
        ws.onerror = function (error) {
            console.log(error)
        }

        // 连接关闭时触发
        ws.onclose = function () {
            console.log('WebSocket已关闭')
        }

        // 点击按钮发送消息
        document.getElementById('sendMessage').onclick = function () {
            var txt = document.getElementById('sendTxt').value
            // 使用连接发送数据
            ws.send(txt)
            document.getElementById('infoBox').innerHTML = txt
        }
    </script>
</head>

<body>

</body>

</html>